#include <string.h>
#include <iostream>
using namespace std;
class String{
public:
    String()
    :_pstr(new char[1])
    {

    }
    //普通构造函数
    String(const char * pstr)
    :_pstr(new char[strlen(pstr)+1]())
    {
        strcpy(_pstr,pstr);
        cout << "String(const char * pstr)"<<endl;
    }
    //移动构造函数
    String(String &&rhs)
        //1.左操作数的指针指向右值申请的堆空间
        //2.让右值的指针断开和堆空间的联系
    :_pstr(rhs._pstr)
    {
        cout << "String(String && rhs)"<<endl;
        rhs._pstr = nullptr;
    }


    String(const String & rhs)
    :_pstr(new char[strlen(rhs._pstr)+1]())
    {
        strcpy(_pstr,rhs._pstr);
    }
    //普通赋值运算符函数
    String & operator=(const String & rhs){
        if(this != &rhs){
            delete [] _pstr;
            _pstr = new char[strlen(rhs._pstr) +1]();
            strcpy(_pstr,rhs._pstr);
        }
    return *this;
    }
    //移动赋值运算符函数
    String & operator=(String && rhs){
        cout<<"String & operator=(String && rhs)"<<endl;
        //1.回收左操作数空间
        delete [] _pstr;
        //2.浅拷贝
        _pstr = rhs._pstr;
        rhs._pstr = nullptr;
        return *this;
    }
    ~String(){
        if(_pstr){
            delete [] _pstr;
            _pstr = nullptr;
        }
    }
friend ostream &operator<<(ostream & os,const String & rhs);
private:
    char * _pstr;
};
ostream & operator<<(ostream & os,const String & rhs){
    if(rhs._pstr){
        os<<rhs._pstr;
    }
    return os;
}
void test(){
    String s1 =std::move(String("hello"));
    cout << s1 <<endl;
    s1 = String("world");
    cout << s1 << endl;
}
int main()
{
    test();
    return 0;
}

